"""
@filename: user.py
@project: flask_project
@author: wlf
@time: 2022-09-04
用户表
"""
from model import db
import datetime
from werkzeug.security import generate_password_hash


class UserManager(db.Model):
    __tablename__ = "user"  # 映射的数据库，不写默认是类名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    _password = db.Column("password", db.String(512), nullable=False)
    cellphone = db.Column(db.String(24), nullable=False)
    school = db.Column(db.String(128), nullable=False)
    admission_date = db.Column(db.String(128), nullable=False)
    delete = db.Column(db.Integer, default=0, nullable=False)

    CreatedAt = db.Column(db.DateTime, default=datetime.datetime.now())
    UpdatedAt = db.Column(db.DateTime, default=None, onupdate=datetime.datetime.now())

    # 使用monitor属性去关联Monitor类、并为Monitor创建反向查询字段 user
    admin = db.relationship("Admin", backref="user", uselist=False)  # 一对一关系
    posts = db.relationship("Posts", backref="user")  # 一对多关系

    def keys(self):
        return ('id', 'username', 'cellphone', 'school', 'admission_date', 'CreateAt')

    def __getitem__(self, item):
        return getattr(self, item)

    def to_json1(self):
        return {
            "username": self.username,
            "cellphone": self.cellphone,
            "school": self.school,
            "admission_date": self.admission_date,
            "Create time": self.CreatedAt.strftime('%Y-%m-%d %H:%M:%S'),
        }

    # 属性包装，定义一些属性之前做一些检测，转换
    # user.password()  ==> print(user.password)
    @property  # -----> password.setter/password.deleter
    def password(self):
        return self._password

    # user.password = xxxx 赋值时就会自动调用如下函数
    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)  # 加密存储

    @classmethod
    def create_user(cls, username, password, cellphone, school, admission_date):
        user = cls()
        user.username = username
        user.password = password     # user._password = generate_password_hash(password)
        user.cellphone = cellphone
        user.school = school
        user.admission_date = admission_date
        db.session.add(user)
        db.session.commit()
